package shop.controller;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import shop.pojo.SysRole;
import shop.pojo.SysUser;
import shop.service.SysRoleService;
import shop.service.SysUserService;
import shop.utils.Constants;
import shop.utils.PageSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

@Controller
@RequestMapping("/user")
public class SysUserController {
    private Logger logger = Logger.getLogger(SysUserController.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    //退出
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }

    //跳转到登录页面
    @RequestMapping("/toLogin")
    public String login(){
        return "login";
    }

    //登录
    @RequestMapping("/login")
    public String doLogin(@RequestParam(value = "account") String account, @RequestParam(value = "password") String password, HttpSession session, HttpServletRequest request){
        //调用service方法，进行用户匹配
        SysUser sysUser =sysUserService.login(account,password);
//        SysUser sysUser = new SysUser();
//        boolean flag = false;
//        //调用service方法，进行用户匹配
//        //查询所有的账户
//        List<SysUser> userList = sysUserService.getAllUserCount(sysUser);
//        List<SysUser> queryList = new ArrayList<>();
//        if ((null != account || null != password) || (!"".equals(account) || !"".equals(password))){
//            for (SysUser user:userList) {
//                //循环匹配
//                if (user.getAccount().equals(account)) {
//
//                    if (user.getPassword().equals(password)){
//                        queryList.add(user);
//
//                        //存储用户信息
//                        session.setAttribute(Constants.USER_SESSION,queryList.get(0));
//                        //登录成功，重定向到toMain接口
//                        return "redirect:/user/toMain";
//                    }else{
//                        request.setAttribute("error","密码不正确！");
//                        flag = true;
//                    }
//                }
//            }
//            if (!flag){
//                request.setAttribute("error","用户名不存在！");
//            }
//            return "login";
//        }else{
//            //提示
//            request.setAttribute("error","用户名或密码不能为空！");
//            //用户不存在，登录失败，跳转到重定向
//            return "login";
//        }
        if(null!=sysUser){
            session.setAttribute(Constants.USER_SESSION,sysUser);
            return "redirect:/user/toMain";
        }else {
            request.setAttribute("error","用户名或密码不正确！");
            return "login";
        }
    }
    //跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session){
        if(session.getAttribute(Constants.USER_SESSION)==null){
            return "redirect:/user/toLogin";
        }
        return "frame";
    }

    @RequestMapping("/list")
    public String getUserList(Model model,String queryRealName,Integer queryRoleId,@RequestParam(defaultValue = "1") Integer pageIndex){
        List<SysUser> userList=null;
        try {
            //设置页面展示条数
            int pageSize =Constants.pageSize;
            System.out.println(pageSize+"展示条数");
            //总条数量
            Integer totalCount =sysUserService.getUserCount(queryRealName,queryRoleId);
            System.out.println(queryRealName+queryRoleId);
            System.out.println(totalCount+"总条数");
            //总页数
            PageSupport pages =new PageSupport();
            pages.setTotalCount(totalCount);
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            int totalPageCount =pages.getTotalPageCount();
            System.out.println(totalPageCount+"总页数");
            //控制首页和尾页
            if(pageIndex>totalPageCount){
                pageIndex=totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList=sysUserService.getUserList(queryRealName,queryRoleId,pageIndex,pageSize);
            model.addAttribute("userList",userList);
            List<SysRole> roleList=null;
            roleList=sysRoleService.getRoleList();
            model.addAttribute("roleList",roleList);
            System.out.println(roleList);
            model.addAttribute("queryRealName",queryRealName);
            System.out.println(queryRealName);
            model.addAttribute("queryRoleId",queryRoleId);
            System.out.println(queryRoleId);
            model.addAttribute("totalPageCount",totalPageCount);
            System.out.println(totalPageCount);
            model.addAttribute("totalCount",totalCount);
            System.out.println(totalCount);
            model.addAttribute("currentPageNo",pageIndex);
            System.out.println(pageIndex);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户列表访问失败");
        }
        return "sysUser/list";
    }

    @GetMapping(value = "/toAdd")
    public String toAdd(HttpServletRequest request){
        return "sysUser/add";
    }

    //提供ajax账号判断
    @GetMapping("/nameExist")
    public ResponseEntity<String> nameExist(HttpServletRequest request){
        String name = request.getParameter("account");
        List list = sysUserService.selectUserByAccount(name);
        if (list.size()>0){
            return ResponseEntity.ok().body("{\"account\":\"exist\"}");
        }else{
            return ResponseEntity.ok().body("{\"account\":\"notexist\"}");
        }
    }

    //文件上传
    public String isExistFilm(MultipartFile attach,HttpServletRequest request){
//        //文件上传
//        String fileName = "";
//        String path = "";
//        try{
//            if (!attach.isEmpty()) {
//                //文件上传
//                fileName = attach.getOriginalFilename();//源文件名称   a.png
//                String suffix = FilenameUtils.getExtension(fileName);//   png
//                fileName = UUID.randomUUID().toString().replace("-", "") + "." + suffix;//ASDGF-DZXFCG12-234DSFDG.png
//                path = request.getSession().getServletContext().getRealPath("/statics/images/"+fileName);
//                File file = new File(path);
//                if (!file.exists()) file.mkdirs();
//                attach.transferTo(file);//传输
//                path = "statics/images/"+fileName;
//            }
//        }catch(Exception e){
//            path = "";
//            e.printStackTrace();
//        }
//        return path;
        // 文件上传
        String fileName = "";
        String path = "";
        try {
            if (!attach.isEmpty()) {
                // 获取文件名和扩展名
                fileName = attach.getOriginalFilename();
                String suffix = FilenameUtils.getExtension(fileName);
                // 生成新的文件名
                fileName = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
                // 构造完整的文件路径
                String uploadDir = request.getSession().getServletContext().getRealPath("/statics/images/");
                File dir = new File(uploadDir);
                // 如果目录不存在，则创建目录
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                // 构造文件对象
                File file = new File(dir, fileName);
                // 传输文件
                attach.transferTo(file);
                // 返回相对于Web应用程序的路径（或根据需要返回完整URL）
                path = "statics/images/" + fileName;
            }
        } catch (Exception e) {
            // 在这里处理异常，例如记录日志或返回错误消息
            e.printStackTrace();
            // 返回错误路径或错误消息
            path = "upload_failed";
        }
        return path;
    }

    //用户添加
    @PostMapping("/add")
    public String add(SysUser sysUser, HttpSession session,Model model,HttpServletRequest request
            ,@RequestParam(value = "idPic",required = false) MultipartFile idPicPath
            ,@RequestParam(value = "workPic",required = false) MultipartFile workPicPath
    ){
        SysUser create =(SysUser) session.getAttribute(Constants.USER_SESSION);
        String path = "";
        if (idPicPath != null && !idPicPath.isEmpty()) {
            path = isExistFilm(idPicPath,request);
            if ("".equals(path)) {
                throw new RuntimeException("证件照上传失败");
            }else {
                sysUser.setIdpicpath(path);
            }
        }
        if (workPicPath != null && !workPicPath.isEmpty()) {
            path = isExistFilm(workPicPath,request);
            if ("".equals(path)) {
                throw new RuntimeException("工作证照片上传失败");
            } else {
                sysUser.setWorkpicpath(path);
            }
        }
        sysUser.setCreateduserid(create.getId());
        sysUser.setCreatedtime(new Date());
        if(sysUserService.add(sysUser)){
            return "redirect:/user/list";
        }else {
            return "sysUser/add";
        }
    }

    //查询用户详细
    @GetMapping("/view/{userid}")
    public String userView(@PathVariable Integer userid,Model model){
        SysUser sysUser = sysUserService.getUserById(userid);
        System.out.println("1111111111111111111111111111"+sysUser);
        model.addAttribute(sysUser);
        return "sysUser/view";
    }

    //去修改页面
    @GetMapping("/toUpdate/{userid}")
    public String toUpdate(@PathVariable Integer userid,Model model){
        SysUser sysUser = sysUserService.getUserById(userid);
        model.addAttribute(sysUser);
        return "sysUser/update";
    }

    @RequestMapping("/update")
    public String toUserUpdate(SysUser sysUser,HttpSession session){
       sysUser.setUpdateduserid( ((SysUser)session.getAttribute(Constants.USER_SESSION)).getId() );
       if(sysUserService.update(sysUser)>0){
           return "redirect:/user/list";
       }
        return "sysUser/update";
    }

//    @GetMapping("/delete/{userid}")
//    public String deleteById(@PathVariable Integer userid,Model model){
//       Integer result = sysUserService.deleteUserById(userid);
//        if(result==1){
//            return "sysUser/list";
//        }else {
//            return "";
//        }
//
//    }

    @GetMapping("/delete")
    public ResponseEntity<Map<String, String>> deleteUser(@RequestParam("method") String method,
                                                          @RequestParam("uid") Integer userId) {
        Map<String, String> responseMap = new HashMap<>();
        System.out.println(userId);
        if ("deleteById".equals(method)) {
            // 检查用户是否存在
            if (sysUserService.userExistsById(userId)) {
                // 删除用户
                Integer isDeleted = sysUserService.deleteUserById(userId);
                if (isDeleted>0) {
                    responseMap.put("delResult", "true");
                } else {
                    responseMap.put("delResult", "false"); // 假设这里表示发生了某种错误，而不是用户不存在
                }
            } else {
                responseMap.put("delResult", "notexist");
            }
        } else {
            // 未知的方法，返回错误
            responseMap.put("delResult", "unknown_method");
        }
        return new ResponseEntity<>(responseMap, HttpStatus.OK);
    }

    //去修改页面
    @RequestMapping("/toUpdatePassword")
    public String toUpdatePassword(HttpSession session,Model model){
        SysUser attribute = (SysUser)session.getAttribute(Constants.USER_SESSION);
        String password = attribute.getPassword();
        model.addAttribute(password);
        return "sysUser/updatePassword";
    }


    // 处理密码验证请求的Controller方法
    @GetMapping("/savePassword")
    public ResponseEntity<?> validateOldPassword(
            @RequestParam(name = "method", required = false, defaultValue = "toUpPassword") String method,
            @RequestParam String oldpassword,
            @RequestParam(required = false) String newpassword ,// 如果此时不需要新密码，可以设置为非必填
            HttpSession session
    ) {
        SysUser attribute = (SysUser)session.getAttribute(Constants.USER_SESSION);
        String password = attribute.getPassword();
        // 验证方法名（虽然在这个例子里可能并不需要）
        if (!"toUpPassword".equals(method)) {
            return new ResponseEntity<>("Invalid method", HttpStatus.BAD_REQUEST);
        }
        // 调用服务层来验证旧密码
        boolean isValid = false;

        if(password.equals(oldpassword)){
            isValid=true;
        }else {
            isValid=false;
        }
        // 准备响应数据
        Map<String, String> responseData = new HashMap<>();
        if (isValid) {
            // 旧密码正确
            responseData.put("result", "true");
        } else {
            // 旧密码不正确
            responseData.put("result", "false");
        }
        // 返回响应
        return new ResponseEntity<>(responseData, HttpStatus.OK);
    }


    //去修改页面
    @PostMapping("/updatePassword")
    public String UpdatePassword(HttpSession session, Model model, HttpServletRequest request, HttpServletResponse response){

        SysUser attribute = (SysUser)session.getAttribute(Constants.USER_SESSION);
        String newPassword = request.getParameter("newPassword");
        String s = sysUserService.updatePassword(attribute.getId(), newPassword);
        if(s.equals("true")){
            model.addAttribute("message","Successfully updated");
            return "sysUser/updatePassword";
        }else {
            return "sysUser/updatePassword";
        }
    }





}
